package com.smart.framework.web.service;

import com.smart.common.core.domain.Email;
import com.smart.common.core.domain.model.RegisterBodyDto;
import com.smart.framework.utils.RegexUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import com.smart.common.constant.CacheConstants;
import com.smart.common.constant.Constants;
import com.smart.common.constant.UserConstants;
import com.smart.common.core.domain.entity.SysUser;
import com.smart.common.core.domain.model.RegisterBody;
import com.smart.common.core.redis.RedisCache;
import com.smart.common.exception.user.CaptchaException;
import com.smart.common.exception.user.CaptchaExpireException;
import com.smart.common.utils.MessageUtils;
import com.smart.common.utils.SecurityUtils;
import com.smart.common.utils.StringUtils;
import com.smart.framework.manager.AsyncManager;
import com.smart.framework.manager.factory.AsyncFactory;
import com.smart.system.service.ISysConfigService;
import com.smart.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;

/**
 * 注册校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

     /**
     * 注册
     */
    @Transactional
    public String register(RegisterBodyDto registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {
            String key = CacheConstants.EMAIL_CODE_KEY + registerBody.getUsername();
            String code = stringRedisTemplate.opsForValue().get(key);
            // 检查获取的值是否为 null，避免空指针异常
            if (code != null) {
                // 去除字符串两端的空格
                code = code.trim();
            }
            if (!Objects.equals(code, registerBody.getEmailCode())) {
                msg = "验证码错误";
            }
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(sysUser);
            // 注册这里先固定写死，给每一个注册的用户是普通用户权限。
            Long[] roleIds = new Long[]{101L};
            userService.insertUserAuth(sysUser.getUserId(), roleIds);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }

    public String sendMailVerify(String emailAddress)
    {
        String msg = "";
        // 1.校验邮箱
        if (!RegexUtils.isEmailInvalid(emailAddress)) {
            // 1.2.如果不符合，返回错误信息
            msg = "不存在的邮箱";
            return msg;
        }
        // 2.检查上一次发送时间，此处并未记录真实发送时间，仅通过验证码的ttl来判断
        String key = CacheConstants.EMAIL_CODE_KEY + emailAddress;
        Long keyExpire = stringRedisTemplate.getExpire(key);
        if (keyExpire != null && CacheConstants.REGISTER_MAIL_CODE_TTL - keyExpire < CacheConstants.SEND_CODE_INTERVAL) {
            // 2.1不合符，拒绝发送
            msg = "发送频繁";
            return msg;
        }
        // 3.检查邮箱是否已经被注册
        if (userService.selectUserByUserName(emailAddress) != null) {
            msg = "该邮箱已被注册";
            return msg;
        }
        // 4.满足条件，生成邮箱验证码
        String code = String.valueOf(RandomUtils.nextInt(100000,1000000));
        // 4.1.存入redis
        stringRedisTemplate.opsForValue().set(key, code, CacheConstants.REGISTER_MAIL_CODE_TTL);
        // 5.发送邮件
        Email email = new Email();
        email.setFrom("星链Health++");
        email.setTo(emailAddress);
        email.setSubject("星链Health++注册验证码");
        email.setText("亲爱的用户：\n" + "你正在注册星链Health++，你的邮箱验证码为：" + code + "，此验证码有效时长5分钟，请勿转发他人。");
        try {
            sendMimeMail(email);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return msg;
    }

    /**
     * 构建复杂邮件信息类
     *
     * @param mail 邮件内容
     * @throws Exception 发送失败
     */
    private void sendMimeMail(Email mail) throws Exception {
        //true表示支持复杂类型
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
        if (mail.getFrom() == null || mail.getFrom().isEmpty()) {
            mail.setFrom("星链Health++");
        }
        //邮件发信人
        messageHelper.setFrom(mailSender.getUsername() + '(' + mail.getFrom() + ')');
        //邮件收信人
        messageHelper.setTo(mail.getTo().split(","));
        //邮件主题
        messageHelper.setSubject(mail.getSubject());
        //邮件内容
        messageHelper.setText(mail.getText());
        //抄送
        if (!isEmpty(mail.getCc())) {
            messageHelper.setCc(mail.getCc().split(","));
        }
        //密送
        if (!isEmpty(mail.getBcc())) {
            messageHelper.setBcc(mail.getBcc().split(","));
        }
        //添加邮件附件
        if (mail.getMultipartFiles() != null) {
            for (MultipartFile multipartFile : mail.getMultipartFiles()) {
                messageHelper.addAttachment(Objects.requireNonNull(multipartFile.getOriginalFilename()), multipartFile);
            }
        }
        //发送时间
        if (isEmpty(mail.getSentDate())) {
            mail.setSentDate(new Date());
        }
        messageHelper.setSentDate(mail.getSentDate());
        //正式发送邮件
        mailSender.send(messageHelper.getMimeMessage());
    }

    private boolean isEmpty(Object str) {
        return (str == null || "".equals(str));
    }
}
